﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Linq;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-03-07 13:46
    /// 描 述：工程数据属性表
    /// </summary>
    public class ec_enginedata_propertyService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_enginedata_propertyEntity> _enginedataPropertyRepository => new Repository<ec_enginedata_propertyEntity>();
        Repository<ec_enginedata_propertyhisEntity> _enginedataPropertyhisRepository => new Repository<ec_enginedata_propertyhisEntity>();
        #endregion
        #region 获取数据

        /// <summary>
        /// 获取位号属性（允许批量）
        /// <summary>
        /// <param name="EngineDataID">工程数据ID（或者多个ID，以逗号隔开）</param>
        /// <param name="ProjectId">项目ID</param>
        /// <param name="CaseID">不为空，则为某个工况下的所有属性。若为空，则为默认工况</param>
        /// <returns></returns>
        public IEnumerable<ec_enginedata_propertyEntity> GetTagPropById(string ProjectId, string EngineDataID, string CaseID = "")
        {
            try
            {
                string tableName = ProjectSugar.TableName<ec_enginedata_propertyEntity>(ProjectId);
                string enginedataTableName = ProjectSugar.TableName<ec_enginedataEntity>(ProjectId);
                var EngineDataIDs = EngineDataID.Split(',');
                var list = _enginedataPropertyRepository.AsQueryable().AS(tableName)
                    .InnerJoin<ec_enginedataEntity>((a, b) => a.EngineDataID == b.EngineDataID)
                    .AS<ec_enginedataEntity>(enginedataTableName)
                    .WhereIF(string.IsNullOrEmpty(CaseID), (a, b) => a.CaseID == b.CaseID)
                    .WhereIF(!string.IsNullOrEmpty(CaseID), (a, b) => a.CaseID == CaseID)
                    .WhereIF(EngineDataIDs != null && EngineDataIDs.Length > 0, (a, b) => EngineDataIDs.Contains(a.EngineDataID) 
                        && a.PropertyName != "HKSK_POSITION_NUM").ToList();
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 获取工程数据属性表数据
        /// <summary>
        /// <param name="ProjectId">项目ID</param>
        /// <param name="EngineDataIds">工程数据ID</param>
        /// <param name="CaseID">工程数据ID</param>
        /// <returns></returns>
        public List<ec_enginedata_propertyEntity> GetEnginePropByList(string ProjectId, List<string> listEngineDataID, string CaseID = "")
        {
            try
            {
                if (listEngineDataID == null || listEngineDataID.Count() == 0)
                {
                    return new List<ec_enginedata_propertyEntity>();
                }
                else
                {
                    string tableName = ProjectSugar.TableName<ec_enginedata_propertyEntity>(ProjectId);
                    string enginedataTableName = ProjectSugar.TableName<ec_enginedataEntity>(ProjectId);

                    var list = _enginedataPropertyRepository.AsQueryable().AS(tableName)
                        .InnerJoin<ec_enginedataEntity>((a, b) => a.EngineDataID == b.EngineDataID).AS<ec_enginedataEntity>(enginedataTableName)
                        .WhereIF(string.IsNullOrEmpty(CaseID), (a, b) => a.CaseID == b.CaseID)
                        .WhereIF(!string.IsNullOrEmpty(CaseID), (a, b) => a.CaseID == CaseID)
                        .Where(a => listEngineDataID.Contains(a.EngineDataID)).ToList();

                    return list;
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 插入一个记录。
        /// 正常是不需要的，因为tag创建时，会根据其objecttype关联的属性，同步插入的。
        /// </summary>
        /// <param name="ProjId"></param>
        /// <param name="TagId"></param>
        /// <param name="prop"></param>
        public void InsertTagProp(string ProjId,string TagId,ec_enginedata_propertyEntity prop)
        {
            var ProjectEntity = _projectRepository.GetById(ProjId);
            _enginedataPropertyRepository.AsInsertable(prop).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
        }

        /// <summary>
        /// 保存工程数据属性表数据（新增）
        /// <param name="engineDataID">工程数据ID</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEngineProp(string ProjectId, List<ec_enginedata_propertyEntity> engineDataPropInsert, List<ec_enginedata_propertyEntity> engineDataPropUpdate, List<ec_enginedata_propertyhisEntity> engineDataPropHis)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    _enginedataPropertyRepository.InsertRange(engineDataPropInsert);
                    _enginedataPropertyRepository.UpdateRange(engineDataPropUpdate);
                    _enginedataPropertyhisRepository.InsertRange(engineDataPropHis);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    //db.InsertByNoMap(engineDataPropInsert, $"ec_enginedata_property_{ ProjectEntity.ProjectIndex}");
                    //db.UpdateByNoMap(engineDataPropUpdate, $"ec_enginedata_property_{ ProjectEntity.ProjectIndex}", "EngineDataPropertyID");
                    //db.InsertByNoMap(engineDataPropHis, $"ec_enginedata_propertyhis_{ ProjectEntity.ProjectIndex}");
                    _enginedataPropertyRepository.AsInsertable(engineDataPropInsert).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    _enginedataPropertyRepository.AsUpdateable(engineDataPropUpdate).AS($"ec_enginedata_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    _enginedataPropertyhisRepository.AsInsertable(engineDataPropHis).AS($"ec_enginedata_propertyhis_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 更新默认工程数据属性
        /// <summary>
        /// <returns></returns>
        public void UpdateEnginePropByDefault(string ProjId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                //string sql = @"SET SQL_SAFE_UPDATES = 0;
                //    UPDATE ec_enginedata_property t3
                //    JOIN ec_enginedata t ON t3.EngineDataID = t.EngineDataID
                //    JOIN ec_objecttypep t1 ON t.ObjectTypeID = t1.ObjectTypeID
                //    JOIN ec_property t2 ON t1.PropertyID = t2.PropertyID AND t3.PropertyName = t2.PropertyName
                //    SET t3.PropertyValue = t2.DefaultValue
                //    WHERE (t2.DefaultValue IS NOT NULL OR t2.DefaultValue != '') AND (t3.PropertyValue IS NULL or t3.PropertyValue = '');
                //    SET SQL_SAFE_UPDATES = 1;";
                //db.ExecuteBySql(sql);
                //遍历项目
                var ProjObj = _projectRepository.GetById(ProjId);
                var x = ProjObj.ProjectIndex;
                var sql = $@"SET SQL_SAFE_UPDATES = 0;
                        UPDATE ec_enginedata_property_{x} t3
                        JOIN ec_enginedata_{x} t on t3.EngineDataID = t.EngineDataID
                        JOIN ec_objecttypep_{x} t1 on t.ObjectTypeID = t1.ObjectTypeID
                        JOIN ec_property_{x} t2 on t1.PropertyID = t2.PropertyID and t3.PropertyName = t2.PropertyName
                        SET t3.PropertyValue = t2.DefaultValue
                        WHERE (t2.DefaultValue IS NOT NULL OR t2.DefaultValue != '') AND (t3.PropertyValue IS NULL or t3.PropertyValue = '');
                        SET SQL_SAFE_UPDATES = 1;";
                SqlSugarHelper.Db.Ado.ExecuteCommand(sql);

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 插入缺少的工程数据属性
        /// <summary>
        /// <returns></returns>
        public void InsertEnginePropByDefault(string ProjId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                //遍历项目
                var ProjObj = _projectRepository.GetById(ProjId);
                var x = ProjObj.ProjectIndex;
                var sql = $@"insert into ec_enginedata_property_{x}
                    select UUID() as EngineDataPropertyID, t3.EngineDataID, t2.PropertyName, t2.DefaultValue as PropertyValue, 'System' as CreateUserID,
                    NOW() as CreateTime, null as UpdateUserID, null as UpdateTime, t5.MeasuringUnitName as MeasuringUnit from ec_objecttype_{x} t
                    join ec_objecttypep_{x} t1 on t.ObjectTypeID = t1.ObjectTypeID
                    join ec_property_{x} t2 on t1.PropertyID = t2.PropertyID
                    join ec_enginedata_{x} t3 on t.ObjectTypeID = t3.ObjectTypeID
                    left join ec_measuring_unit_{x} t5 on t2.DefaultUnit = t5.MeasuringUnitID
                    left join ec_enginedata_property_{x} t4 on t2.PropertyName = t4.PropertyName and t3.EngineDataID = t4.EngineDataID
                    where t4.EngineDataPropertyID is null";
                SqlSugarHelper.Db.Ado.ExecuteCommand(sql);

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

    }
}
